package com.kennedy.atoupdate.web.controller;

import com.github.pagehelper.PageInfo;
import com.kennedy.atoupdate.beans.CheckUpdateResult;
import com.kennedy.atoupdate.beans.DeviceInfo;
import com.kennedy.atoupdate.beans.VersionInfo;
import com.kennedy.atoupdate.beans.common.ResultMsg;
import com.kennedy.atoupdate.service.DeviceInfoService;
import com.kennedy.atoupdate.service.GroupInfoService;
import com.kennedy.atoupdate.service.VersionGroupService;
import com.kennedy.atoupdate.service.VersionInfoService;
import com.kennedy.atoupdate.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/versionInfo")
public class VersionInfoController {
    @Autowired
    private VersionInfoService versionInfoService;
    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private VersionGroupService versionGroupService;


    @GetMapping("/toList")
    public String toLogin() {
        return "versioninfo/list";
    }

    @GetMapping("/toAdd")
    public String toAdd() {
        return "versioninfo/add";
    }

    @GetMapping("/getListByPage")
    @ResponseBody
    public PageInfo<VersionInfo> getListByPage(VersionInfo versionInfo) {
        List<VersionInfo> huaSes = versionInfoService.getListByPage(versionInfo);
        return new PageInfo<VersionInfo>(huaSes);
    }

    @PostMapping("/add")
    @ResponseBody
    public ResultMsg add(VersionInfo versionInfo, @RequestParam("updatePkg") MultipartFile file, HttpServletRequest request) {
        getVersion(versionInfo, file);
        if (versionInfoService.getVersionInfoByVersionAndType(versionInfo.getVersion(), versionInfo.getType()) == null) {
            try {
                versionInfoService.insert(versionInfo, file);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ResultMsg.success();
        } else {
            return ResultMsg.error("此版本已存在");
        }

    }

    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public ResultMsg delete(@PathVariable("id") Long id) {
        try {
            versionInfoService.delete(id);
        } catch (Exception e) {
            ResultMsg.error();
        }
        return ResultMsg.success();

    }

    private void getVersion(VersionInfo versionInfo, @RequestParam("updatePkg") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        int num = prefix.length();//得到后缀名长度
        versionInfo.setVersion(fileName.substring(0, fileName.length() - num));
    }

    @GetMapping("/checkUpdate")
    @ResponseBody
    public ResultMsg<CheckUpdateResult> checkUpdate(@RequestParam(value = "version", required = true) String version, @RequestParam(value = "type", required = true) Integer type, @RequestParam(value = "deviceId", required = false) String deviceId) {
        DeviceInfo deviceInfo = null;
        if (StringUtils.hasText(deviceId)) {
            deviceInfo = deviceInfoService.findByDeviceId(deviceId);
            if (null == deviceInfo) {
                // 保存设备唯一标识
                deviceInfoService.insert(new DeviceInfo(deviceId, DateUtil.getCurrentTime()));
            }
        }
        // 获取旧版本号
        VersionInfo lastVersionInfo = versionInfoService.getLastVersionInfoByType(type);
        if (versionInfoService.getVersionInfoByVersionAndType(version, type) != null) {
            if (version.equals(lastVersionInfo.getVersion())) {
                return ResultMsg.error("已是最新版本", 1);
            } else {
                if (null != deviceInfo) {
                    // 判断该版本是否在推送组中
                    if (!versionGroupService.checkIsPushGroup(lastVersionInfo.getId(), deviceInfo.getGroupId())) {
                        return ResultMsg.error("已是最新版本", 1);
                    }
                }
                VersionInfo versionInfoQuery = new VersionInfo();
                versionInfoQuery.setVersion(version);
                VersionInfo oldVersionInfo = versionInfoService.selectOne(versionInfoQuery);
                return ResultMsg.success(new CheckUpdateResult(true, "http://obd.careryun.com:88/static/atoupdate/" + type + "/updatepkg/" + version + "/update.zip", lastVersionInfo.getVersion(), oldVersionInfo.getSize(), lastVersionInfo.getRemark(), lastVersionInfo.getUpdateTime(), oldVersionInfo.getMd5()));
            }
        } else {
            return ResultMsg.error("版本号不正确");
        }
    }

    @GetMapping("/editPushGroup/{id}")
    public String editPushGroup(@PathVariable("id") Long id, ModelMap modelMap) {
        modelMap.put("id", id);
        return "versioninfo/edit_push_group";
    }

}
